package com.wmm.jinhong;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.common.dialog.MyDialog;
import com.common.net.mywidget.LoadingDialog;
import com.common.util.SPUtils;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class SCCKActivity extends AppCompatActivity {
    ScanReceiver receiver;
    IntentFilter filter;
    @BindView(R.id.et_yd_code)
    EditText etYdCode;
    @BindView(R.id.et_gp_code)
    EditText etGpCode;
    @BindView(R.id.txt_scan_num)
    TextView txtScanNum;
    @BindView(R.id.txt_car_number)
    TextView txtCarNumber;
    @BindView(R.id.list)
    ListView listView;
    private String gpCode = "";
    private String ydCode = "";
    LoadingDialog dialog;
    List<GangPingBean> list = new ArrayList<>();
    private SCRKAdapter adapter;
    private boolean isSubmit=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scck);
        ButterKnife.bind(this);
        receiver = new ScanReceiver();
        filter = new IntentFilter(ScannerService.ACTION);
        dialog = new LoadingDialog(this);
        adapter = new SCRKAdapter(this, list);
        DataSetObserver dataSetObserver = new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                txtScanNum.setText("已扫描数: "+adapter.getCount());
            }
        };
        adapter.registerDataSetObserver(dataSetObserver);
        listView.setAdapter(adapter);
        etYdCode.requestFocus();
//        getCarNumber();
    }

    private void getCarNumber() {
        final RequestParams requestParams = new RequestParams();
        requestParams.put("sFaYunDanHao", ydCode);
        requestParams.put("sYu", SPUtils.get(this, "YuInfo", ""));
        HttpUtils.post(Constant.SAOMA_SONGHUODAN_ONE, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("huan", responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
                dialog.show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    txtCarNumber.setText("车牌号: "+responseString);
            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_HOME){
            Intent mIntent = new Intent();
            mIntent.setAction(Intent.ACTION_MAIN);
            mIntent.addCategory(Intent.CATEGORY_HOME);
            startActivity(mIntent);
        }
        return super.onKeyDown(keyCode, event);
    }
    private void getBottleInfo() {
        final RequestParams requestParams = new RequestParams();
        requestParams.put("sPingHao", gpCode);
        requestParams.put("sYu", SPUtils.get(this, "YuInfo", ""));
        HttpUtils.post(Constant.SAOMAGANGPING, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("huan", responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
                dialog.show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject object = new JSONObject(responseString);
                    if (object.getInt("success") == 0) {
                        JSONArray array = object.getJSONArray("data");
                        JSONObject object1=array.getJSONObject(0);
                        if(object1.getInt("IsFull")==0){
                            T.showShort(SCCKActivity.this,gpCode+"是空瓶，请先入库");
                            return;
                        }
                        GangPingBean bean=new GangPingBean();
                        bean.setGangPingHao(object1.getString("GangPingHao"));
                        bean.setInvName(object1.getString("InvName"));
                        bean.setcInvStd(object1.getString("cInvStd"));
                        bean.setcInvCode(object1.getString("cInvCode"));
                        list.add(bean);
                        adapter.notifyDataSetChanged();
                    } else {
                        T.showShort(SCCKActivity.this, object.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注册接收器
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onPause() {
        // 卸载接收器
        unregisterReceiver(receiver);
        super.onPause();
    }

    @OnClick(R.id.btn_submit)
    public void onViewClicked() {
        if(list.size()<=0){
            T.showShort(this,"提交记录条数为0");
            return;
        }
        if(!isSubmit) {
            firstSubmit();
        }else{
            T.showShort(this,"请勿重复出库");
        }
    }
    // 将 student 对象的值存储到 ContentValues 中
    private ContentValues studentToContentValues(Bean bean) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("type", bean.type);
        contentValues.put("list", bean.list);
        contentValues.put("ydhao",bean.ydhao);
        contentValues.put("kehu",bean.kehu);
        contentValues.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return contentValues;
    }
    private void firstSubmit(){
        JSONArray array=null;
        try {
            array=new JSONArray();
            JSONObject object;
            final List<GangPingBean> list=adapter.getLists();
            for(int i=0;i<list.size();i++){
                object=new JSONObject();
                object.put("钢瓶号",list.get(i).getGangPingHao());
                object.put("介质",list.get(i).getInvName());
                object.put("规格",list.get(i).getcInvStd());
                object.put("物料编码",list.get(i).getcInvCode());
                object.put("充前重量","");
                object.put("充后重量","");
                array.put(object);
            }
            RequestParams requestParams=new RequestParams();
            requestParams.put("sJson",array.toString().replace("=",":"));
            requestParams.put("sFaYunDanHao",etYdCode.getText().toString());
            requestParams.put("sStorageScanID",SPUtils.get(this,"UserName","").toString());
            requestParams.put("sSyu",SPUtils.get(this,"YuInfo","").toString());
            requestParams.put("sTiSongHuoDanHao","");
            HttpUtils.post(Constant.SCCKURL, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    MyDialog.showMaterialDialog(getSupportFragmentManager(), "提示", "网络信号不好，需要保存记录之后提交吗", "继续提交", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            firstSubmit();
                        }
                    }, "保存返回", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bean bean=new Bean();
                            bean.type="2";
                            bean.ydhao=etYdCode.getText().toString();
                            bean.kehu="";
                            bean.list=new Gson().toJson(list);
                            ContentValues contentValues=studentToContentValues(bean);
                            MyApp.getInstance().insert(SQLiteDbHelper.TABLE_STUDENT,null,contentValues);
                            finish();
                        }
                    }).show();
                }

                @Override
                public void onStart() {
                    super.onStart();
                    dialog.show();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    dialog.dismiss();
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if(responseString.contains("true")){
                        T.showShort(SCCKActivity.this,"出库成功,总出库量"+list.size());
                        isSubmit=true;
                        finish();
                    }else{
                        T.showShort(SCCKActivity.this,"出库失败");
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if(!isSubmit&&list.size()>0){
            MyDialog.showMaterialDialog(getSupportFragmentManager(), "提示", "数据未提交，继续退出吗？", "退出", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            }, "再想想", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            }).show();
            return;
        }
        finish();
    }

    public class ScanReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            if (bundle.getString(ScannerService.BAR_CODE).startsWith("SP")) {
                ydCode = bundle.getString(ScannerService.BAR_CODE);
                etYdCode.setText(ydCode);
                etYdCode.requestFocus();
                getCarNumber();
            } else {
                if("".equals(etYdCode.getText().toString().trim())){
                    T.showShort(SCCKActivity.this,"请先扫描运单号");
                    return;
                }
                if(gpCode.equals( bundle.getString(ScannerService.BAR_CODE))){
                    return;
                }
                gpCode = bundle.getString(ScannerService.BAR_CODE);
                etGpCode.requestFocus();
                etGpCode.setText(gpCode);
                for(int i=0;i<list.size();i++){
                    if(list.get(i).getGangPingHao().equals(gpCode)){
                        T.showShort(SCCKActivity.this,"钢瓶已扫过");
                        return;
                    }
                }
                getBottleInfo();
            }
//            mEditText.append("barcode: "
//                    + bundle.getString(ScannerService.BAR_CODE) + "\ntype: "
//                    + bundle.getString(ScannerService.CODE_TYPE) + "\nlength: "
//                    + bundle.getInt(ScannerService.LENGTH) + "\n");
        }
    }
}
